package com.hnucm.c201901020241.my;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.pojo.User;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class UpdatePersonalInformation extends AppCompatActivity implements View.OnClickListener{
    private TimePickerView  pvCustomLunar;
    String name,ac,psw,signature,sex,birthday,grade,college,infor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_personal_information);
        initLunarPicker();
        init_view();//初始化部分部件的值
//        接收广播
        IntentFilter filter1 = new IntentFilter(Update_name.action);
        registerReceiver(broadcastReceiver, filter1);

        IntentFilter filter2 = new IntentFilter(Update_signature.action);
        registerReceiver(broadcastReceiver1,filter2);

    }
    BroadcastReceiver broadcastReceiver1=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            signature=intent.getStringExtra("signature");
            ((TextView)findViewById(R.id.textView49)).setText(signature);
            SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("signature",signature);
            editor.commit();
        }
    };
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            name=intent.getStringExtra("name");
            ((TextView)findViewById(R.id.textView47)).setText(name);
            SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("name",name);
            editor.commit();
        }
    };

    private void init_view() {
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_MULTI_PROCESS);
        ac= sharedPreferences.getString("account","");
        psw= sharedPreferences.getString("password","");
        name= sharedPreferences.getString("name", "null");
        signature= sharedPreferences.getString("signature","");
        sex= sharedPreferences.getString("sex","");
        birthday= sharedPreferences.getString("birthday","");
        grade= sharedPreferences.getString("grade","");
        college= sharedPreferences.getString("college","");
        ((TextView)findViewById(R.id.textView47)).setText(name);
        ((TextView)findViewById(R.id.textView49)).setText(signature);
        ((TextView)findViewById(R.id.textView53)).setText(sex);
        ((TextView)findViewById(R.id.textView55)).setText(birthday);
        ((TextView)findViewById(R.id.textView57)).setText(grade);
        ((TextView)findViewById(R.id.textView59)).setText(college);
    }


    private void initLunarPicker() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2069, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                TextView textView=findViewById(R.id.textView55);
                textView.setText(getTime(date));
                infor=getTime(date);
                Toast.makeText(UpdatePersonalInformation.this, getTime(date), Toast.LENGTH_SHORT).show();
                update_user("birthday");
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {
                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.dismiss();
                            }
                        });
                        //公农历切换
                        CheckBox cb_lunar = (CheckBox) v.findViewById(R.id.cb_lunar);
                        cb_lunar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                pvCustomLunar.setLunarCalendar(!pvCustomLunar.isLunarCalendar());
                                //自适应宽
                                setTimePickerChildWeight(v, isChecked ? 0.8f : 1f, isChecked ? 1f : 1.1f);
                            }
                        });

                    }

                    /**
                     * 公农历切换后调整宽
                     * @param v
                     * @param yearWeight
                     * @param weight
                     */
                    private void setTimePickerChildWeight(View v, float yearWeight, float weight) {
                        ViewGroup timePicker = (ViewGroup) v.findViewById(R.id.timepicker);
                        View year = timePicker.getChildAt(0);
                        LinearLayout.LayoutParams lp = ((LinearLayout.LayoutParams) year.getLayoutParams());
                        lp.weight = yearWeight;
                        year.setLayoutParams(lp);
                        for (int i = 1; i < timePicker.getChildCount(); i++) {
                            View childAt = timePicker.getChildAt(i);
                            LinearLayout.LayoutParams childLp = ((LinearLayout.LayoutParams) childAt.getLayoutParams());
                            childLp.weight = weight;
                            childAt.setLayoutParams(childLp);
                        }
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
//            修改昵称
            case R.id.constraintLayout11:
                intent=new Intent(UpdatePersonalInformation.this,Update_name.class);
                startActivity(intent);
                break;
//                修改个性签名
            case R.id.constraintLayout10:
                intent=new Intent(UpdatePersonalInformation.this,Update_signature.class);
                startActivity(intent);
                break;
//                修改密码
            case R.id.constraintLayout12:
                intent=new Intent(UpdatePersonalInformation.this,Update_password.class);
                startActivity(intent);
                break;
//                修改性别
            case R.id.constraintLayout14:
                intent=new Intent(UpdatePersonalInformation.this,Dialog3Activity.class);
                intent.putExtra("choose","sex");
                startActivityForResult(intent,0);
                break;
//                修改生日
            case R.id.constraintLayout15:
                pvCustomLunar.show();
                break;
//                修改年级
            case R.id.constraintLayout16:
                intent=new Intent(UpdatePersonalInformation.this,Dialog2Activity.class);
                intent.putExtra("choose","nianji");
                startActivityForResult(intent,0);
                break;
//                修改学院
            case R.id.constraintLayout17:
                intent=new Intent(UpdatePersonalInformation.this,Dialog2Activity.class);
                intent.putExtra("choose","xueyuan");
                startActivityForResult(intent,0);
                break;
//                返回上一级
            case R.id.imageView19:
                finish();
                break;
        }
    }

    private void update_user(String op) {
        if(op.equals(""))return ;
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if(op.equals("sex")){
            editor.putString("sex",infor);
            sex=infor;
            ((TextView)findViewById(R.id.textView53)).setText(sex);
        }
        if(op.equals("birthday")){
            editor.putString("birthday",infor);
            birthday=infor;
            ((TextView)findViewById(R.id.textView54)).setText(birthday);
        }
        if(op.equals("nianji")){
            editor.putString("grade",infor);
            grade=infor;
            ((TextView)findViewById(R.id.textView57)).setText(grade);
        }
        if(op.equals("xueyuan")){
            editor.putString("college",infor);
            college=infor;
            ((TextView)findViewById(R.id.textView59)).setText(college);
        }
        editor.commit();
        x.Ext.init(getApplication());
        RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/updateUser?");
        requestParams.addQueryStringParameter("account", ac);
        requestParams.addQueryStringParameter("password", psw);
        requestParams.addQueryStringParameter("name", name);
        requestParams.addQueryStringParameter("signature", signature);
        requestParams.addQueryStringParameter("sex", sex);
        requestParams.addQueryStringParameter("birthday", birthday);
        requestParams.addQueryStringParameter("grade", grade);
        requestParams.addQueryStringParameter("college", college);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.equals("1"))
                    Toast.makeText(UpdatePersonalInformation.this, "修改成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(UpdatePersonalInformation.this, "网络出现异常错误，请稍后", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String choose;
        if(data!=null) {
            infor=data.getStringExtra("op");
            choose=data.getStringExtra("choose");
        }
        else{
            infor="";
            choose="";
        }
//        Log.i("test",infor);
//        然后进行更新的操作
        update_user(choose);
    }
}